package com.start.security;

import com.alibaba.fastjson2.JSONObject;
import com.start.common.details.BaseUserDetails;
import com.start.common.std.StartBaseSingleton;
import com.start.common.std.StartSingletonFactory;
import com.start.common.tools.SpringContextTools;
import com.start.security.data.permission.StartBaseUserProp;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 用户上下文管理器
 */
public class StartUserContextManage extends StartBaseSingleton<StartUserContextManage> {
    private static final ConcurrentMap<String, StartBaseUserProp> userPropMap = new ConcurrentHashMap<>();


    public StartUserContext getUserContext(BaseUserDetails userDetails) {
        JSONObject prop = getUserProp(userDetails);
        return StartUserContext.create(userDetails, prop);
    }

    public JSONObject getUserProp(BaseUserDetails userDetails) {
        return getUserContext(userDetails.getStartUserType(), userDetails.getUserId());
    }

    public JSONObject getUserContext(String startUserKey) {
        String[] split = startUserKey.split(":");
        return getUserContext(split[0], split[1]);

    }

    public JSONObject getUserContext(String startUserType, String userId) {
        StartBaseUserProp startBaseUserProp = userPropMap.get(startUserType);
        if (startBaseUserProp == null) {
            throw new RuntimeException("未知用户体系");
        }
        JSONObject jsonObject = startBaseUserProp.loadUserProp(userId);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        return jsonObject;
    }


    /**
     * 调用初始化函数
     */
    @Override
    public void init() {
        Map<String, StartBaseUserProp> beans = SpringContextTools.getBeans(StartBaseUserProp.class);
        beans.values().forEach(e -> {
            String userType = e.startUserType();
            userPropMap.put(userType, e);
        });
    }

    public static StartUserContextManage getInstance() {
        return StartSingletonFactory.get(StartUserContextManage.class);
    }


}
